/*
***************************** 
*    author:unrpyc          * 
*    date:2022/1/21         *
*    libraries:[            *
*        'jsonwebtoken',    *
*        'express',         *
*        'mysql',           *
*        'readline-sync',   *
*        'body-parser',     *
*        'silly-datetime',  *
*        'fs'               *
*    ]                      *
*****************************
*/
//use smartSystem;加这多此一举的一句sql为了查询结果能够返回OkPacket{......}
//引用第三方库
let sillydate = require('silly-datetime')
let jsonwebtoken = require('jsonwebtoken')
let mysql = require('mysql')
//let http = require('http')
let path = require('path')
let readline = require('readline-sync')
let express = require('express')
let bodyParser = require('body-parser')
let fs = require("fs");
let utils = require('./utils')
let config = require('./config.json')
let logger = require('./logger.js')
let tencentNews = require('./crawler/tencent_crawler')
let md5 = require('node-md5')
//设置基础变量以及常量
const TRUE = 1
const FALSE = 0
let PORT = config.PORT
let IP = config.IP
let HOST = config.HOST
let PASSWORD = config.PASSWORD
let USER = config.USER
let POST = config.POST
let HTTP = config.HTTP
let DATABASENAME = "smartsystem"

const CHECK_GET_USER_INFORMATION = ['token', 'userId']
const CHECK_GET_USER_ORDER_DETAILS = ['token', 'userId', 'orderId']
const CHECK_USER_REGISTER = ['nickName', 'userName', 'userPassword', 'idNumber', 'sex', 'birth', 'face']
const CHECK_USER_LOGIN = ['userName', 'userPassword']
const CHECK_GET_USER_FEEDBACK_DETAILS = ['token', 'userId', 'feedbackId']
const CHECK_UPLOAD_USER_ORDER = ['token', 'orderNum', 'orderContent', 'orderStatus', 'classification', 'orderDate', 'userId']
const CHECK_UPLOAD_USER_FEEDBACK = ['token', 'userId', 'feedbackContent', 'feedbackDate']
const CHECK_UPDATE_PASSWORD = ['token', 'userName', 'userId', 'idNumber', 'newPassword']
const CHECK_GET_LIST = ['token', 'userId', 'pageNum', 'pageSize']
const CHECK_GET_COMMENTS_LIST = ['token', 'userId', 'targetId', 'classification', 'pageNum', 'pageSize']
const CHECK_GET_NEWS_DETAIL = ['token', 'userId', 'newsId']
const CHECK_LIKE_NEWS_DETAILS = ['token', 'userId', 'newsId', 'like']
const CHECK_VIEW_NEWS_DETAILS = ['token', 'userId', 'newsId', 'view']
const CHECK_SEARCH_NEWS = ['token', 'userId', 'keywords']
const CHECK_UPLOAD_COMMENTS = ['token', 'userId', 'commentContent', 'commentDate', 'classification', 'targetId']
const CHECK_GET_DOCTOR_LIST = ['token', 'userId', 'departmentId', 'pageNum', 'pageSize']
const CHECK_GET_AVAILABLE_LIST = ['token', 'userId', 'doctorId', 'pageNum', 'pageSize']
const CHECK_UPLOAD_HOPORDER = ['token', 'userId', 'patientId', 'hospitalId', 'departmentId', 'doctorId', 'orderDate', 'createDate']
const CHECK_GET_DEPARTMENT_LIST = ['token', 'userId', 'hospitalId', 'pageNum', 'pageSize']
const CHECK_GET_HOPORDER_DETAILS = ['token', 'userId', 'hopId']
const CHECK_UPLOAD_PATIENT = ['token', 'userId', 'patientName', 'birth', 'phoneNum', 'sex', 'address']

//密钥
const USER_SECRETORPRIVATEKEY = "uNrPyC_USER";
const ADMINSTRATOR_SECRETORPRIVATEKEY_SUPER = "UnRpYc_ADMINSTRATOR_super";
const ADMINSTRATOR_SECRETORPRIVATEKEY_DEVELOPMENT = "UnRpyc_ADMINSTRATOR_development"
const ADMINSTRATOR_SECRETORPRIVATEKEY_CUSTOMER = "UnRpyc_ADMINSTRATOR_customer"

//个人中心模块接口
const URL_USER_LOGIN = "/user/login"
const URL_USER_REGISTER = "/user/register"
const URL_GET_USER_INFORMATION = "/getUserInformation"
const URL_GET_USER_ORDER_DETAILS = "/getUserOrderDetails"
const URL_GET_USER_FEEDBACK_DETAILS = "/getUserFeedbackDetails"
const URL_UPDATE_PASSWARD = "/updateUserPassword"
const URL_UPDATE_USER_INFORMATION = "/updateUserInformation"
const URL_UPLOAD_USER_FEEDBACK = "/uploadUserFeedback"
const URL_UPLOAD_USER_ORDER = "/uploadUserOrder"
const URL_UPLOAD_COMMENTS = "/uploadComments"
const URL_GET_COMMENTS_LIST = "/getCommentsList"

//新闻模块接口
const URL_GET_NEWS_LIST = "/getNewsList"
const URL_GET_HISTORY_NEWS_LIKE_LIST = "/getNewsLikeList"
const URL_GET_HISTORY_NEWS_VIEW_LIST = "/getNewsViewList"
const URL_GET_NEWS_DETAILS = "/getNewsDetails"
const URL_LIKE_NEWS_DETAILS = "/newsLike"
const URL_VIEW_NEWS_DETAILS = "/newsView"
const URL_SEARCH_NEWS = "/searchNews"
const URL_TOTALE_PAGES = "/getTotalPages"

//医疗预约模块接口
const URL_GET_HOSPITAL_LIST = "/getHospitalList"
const URL_GET_DEPARTMENT_LIST = "/getDepartmentList"
const URL_UPLOAD_PATIENT = "/uploadPatient"
const URL_UPDATE_PATIENT = "/updatePatient"
const URL_GET_PATIENT_LIST = "/getPatientList"
const URL_GET_HOPORDER_LIST = "/getHopOrderList"
const URL_GET_HOPORDER_DETAILS = "/getHopOrderDetails"
const URL_GET_DOCTOR_LIST = "/getDoctorsList"
const URL_GET_AVAILABLE_LIST = "/getAvailableList"
const URL_UPLOAD_HOPORDER = "/uploadHopOrder"

//养老院 

//智慧养老模块接口


//资源其他接口
const URL_GET_GUIDE_PICTURE = "/getGuidePicture"

//管理员专用接口
const URL_GET_USER_LIST = "/getUserList"
const URL_GET_USER_ORDER_LIST = "/getUserOrderList"
const URL_GET_USER_FEEDBACK_LIST = "/getUserFeedbackList"
const UPDATE_USER_FEEDBACK = "/updateUserFeedback"
const UPDATE_USER_ORDER = "/updateUserOrder"
const URL_UPLOAD_NEWS = "/uploadNews"
const URL_UPDATE_NEWS = "/updateNews"
const URL_MODERATION_COMMENTS = "/moderationComments" 
const crawlerTencent = "/crawlerTencentNews"
//门诊预约模块接口

//智慧养老模块接口

// option1 = readline.question("enter the external ip address (default:127.0.0.1):")
// option2 = readline.question("enter specify a port number on which the service runs (default:8888):")
// option3 = readline.question("enter the ip address of the database server (default:localhost):")
// option4 = readline.question("enter the database server port number (default:3306):")
// option5 = readline.question("enter your database account (default:root):")
// option6 = readline.question("enter the database password (default:):")
// option7 = readline.question("enter http protocol (default:http):")
// setNet(option1, option2, option3, option4, option5, option6, option7)

//连接池
let pool = mysql.createPool({
    host: HOST,
	user: USER,
    database: DATABASENAME,
	password: PASSWORD,
    post: POST,
	protocol: 'mysql',
	multipleStatements: true,
	connectionLimit: 100000
})

//测试数据库连接
pool.getConnection((err, conn) => {
	if (err) {}
	conn.query("SELECT VERSION()",
	(err, data) => {
		if (err) {
            logger.info('info', "连接测试失败，具体错误信息请查看日志。")
			logger.error('error', err)
		} else {
			logger.info('info', 'Database connection successful');
			logger.info('info', 'Database initialization created successfully')
		}
		conn.release()
	})
    
});

let app = express()

//设置全局响应头
app.all('*', (req, res, next) => {
  const { origin, Origin, referer, Referer } = req.headers;
  const allowOrigin = origin || Origin || referer || Referer || '*'; 
    res.header("Access-Control-Allow-Origin", allowOrigin);
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "POST,GET");
    res.header("X-Powered-By", 'Express');
    res.header("Content-Type", "application/json;charset=utf-8")
    next()
});

app.use(logger.netLog());
//设置用于处理请求数据的中间件bodyParser,且请求体最大为2MB
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({limit : '2100000kb'}))


//处理个人中心模块的请求
app.post(URL_USER_REGISTER, (req, res) => {
    if (utils.checkParameters(CHECK_USER_REGISTER, req.body)) {
        logger.info('info', URL_USER_REGISTER)
        let userName = req.body.userName
        let userPassword = req.body.userPassword
        let idNumber = req.body.idNumber
        let nickName = req.body.nickName
        let sex = req.body.sex
        let createDate = sillydate.format(new Date(), 'YYYY-MM-DD HH:mm')
        let birth = sillydate.format(req.body.birth, 'YYYY-MM-DD HH:mm')
        let picName = new Date().getTime()

        //路径从app.js级开始找--
        userName = md5(userName)
        let urlPath = './albums/'+ userName + '/userFacePic/'
        let temp = '/albums/'+ userName + '/userFacePic/'
        let facePath = HTTP + '://' + IP + ':' + PORT + temp + picName + '.jpg'
        sql = sql = 'use smartSystem;insert into userInfo values ("' + userName + '", "新用户", "' + nickName + '", "' + createDate + '", "' + facePath +'", "' + birth + '", "暂无", "' + sex +'" , "' + userPassword + '", NULL , "' + idNumber + '");'
        utils.startOperations(pool, sql).then((rv) => {
            if (rv) {
                utils.startPictureOperations(req.body.face, urlPath, picName).then((rv) => {
                    if (rv) {
                        logger.info('info', '{"msg":"注册成功"}')
                        res.send('{"msg":"注册成功"}')  
                    } else {
                        logger.info('info', '{"msg":"头像未成功上传"}')
                        res.status(501).send('{"msg":"头像未成功上传"}')  
                    }
                })
            }
            else {
                logger.info('info', '{"msg":"操作异常"}')
                res.status(500).send('{"msg":"操作异常"}')  
            }
        }) 
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
}) 

app.post(URL_USER_LOGIN, (req, res) => {
    logger.info('info', URL_USER_LOGIN)
    if(utils.checkParameters(CHECK_USER_LOGIN, req.body)) {
        let userName = req.body.userName
        let userPassword = req.body.userPassword
        sql = 'use smartSystem;select userId from userInfo where userName = "' + userName + '" and userPassword = "' + userPassword + '";'
        utils.startOperations(pool, sql).then((rv) => {
            if(rv) {
                logger.info('info', rv)
                if (rv.length === 0) {
                    logger.info('info', '{"msg":"登录异常"}')
                    res.status(500).send('{"msg":"登录异常"}')
                } else {
                    logger.info('info', rv)
                    res.send('{"msg":"登陆成功","data":{"token":"'+ createToken({
                        'userId':rv[0].userId
                    }, USER_SECRETORPRIVATEKEY) +'"}}')
                }

            } else {
                logger.info('info', '{"msg":"登录异常"}')
                res.status(500).send('{"msg":"登录异常"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }

})

app.post(URL_GET_USER_FEEDBACK_DETAILS, (req, res) => {
    logger.info('info', URL_GET_USER_FEEDBACK_DETAILS)
    if(utils.checkParameters(CHECK_GET_USER_FEEDBACK_DETAILS, req.body)) {
        let feedbackId = req.body.feedbackId
        let userId = req.body.userId
        let token = req.body.token;
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select * from feedbackinfo where userId = ' + userId + ' and feedbackId = ' + feedbackId + ';'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
    
})

app.post(URL_GET_USER_FEEDBACK_LIST, (req, res) => {
    logger.info('info', URL_GET_USER_FEEDBACK_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from feedbackinfo where userId = ?;',
                             'select * from feedbackinfo where userId = ? limit ?, ?;']
        let parameters = [[userId],[userId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_USER_INFORMATION, (req, res) => {
    logger.info('info', URL_GET_USER_INFORMATION)
    if(utils.checkParameters(CHECK_GET_USER_INFORMATION, req.body)) {
        let userId = req.body.userId
        let token = req.body.token;
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select * from userInfo where userId = ' + userId + ';'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_USER_ORDER_DETAILS, (req, res) => {
    logger.info('info', URL_GET_USER_ORDER_DETAILS)
    if(utils.checkParameters(CHECK_GET_USER_ORDER_DETAILS, req.body)) {
        let orderId = req.body.orderId
        let userId = req.body.userId
        let token = req.body.token;
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select * from orderInfo where userId = ' + userId + ' and orderId = ' + orderId + ';'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_USER_ORDER_LIST, (req, res) => {
    logger.info('info', URL_GET_USER_ORDER_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from orderinfo where userId = ?;',
                             'select * from orderinfo where userId = ? limit ?, ?;']
        let parameters = [[userId],[userId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPDATE_PASSWARD, (req, res) => {
    logger.info('info', URL_UPDATE_PASSWARD)
    if(utils.checkParameters(CHECK_UPDATE_PASSWORD, req.body)) {
        let userId = req.body.userId
        let userName = req.body.userName
        let idNumber = req.body.idNumber
        let newPassword = req.body.newPassword
        let token = req.body.token;
        sql = 'use smartSystem;update userInfo set userPassword = "'+ newPassword +'" where idNumber = "'+ idNumber +'" and userName = "'+ userName +'";'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv) {
                        logger.info('info', '{"msg":"更改成功"}')
                        res.send('{"msg":"更改成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"更改异常"}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }

})

app.post(URL_UPDATE_USER_INFORMATION, (req, res) => {
    logger.info('info', URL_UPDATE_USER_INFORMATION)
    let sql_templates = []
    let parameters = []
    try {
        let userId = req.body.userId
        let token = req.body.token
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                for(item in req.body) {
                    if (item === "token" || item === "userId") {
                        continue
                    } else {
                        sql_templates.push('update userInfo set '+item+' = ? where userId = '+userId+';')
                        parameters.push([req.body[item]])
                    }
                }
                logger.info('info', sql_templates)
                logger.info('info', parameters)
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    logger.info('info', rv)
                    if (rv.length !== 0) {
                        logger.info('info', '{"msg":"更改成功"}')
                        res.send('{"msg":"更改成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"更改失败}')
                    }
                }).catch((err) => {
                    logger.error('error', err)
                    res.status(406).send('{"msg":"更改异常"}')
                }) 
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } catch (err) {
        logger.info('info', '{"msg":"更改异常"}')
        logger.error('error', err)
        res.status(402).send('{"msg":"更改异常"}')
    }
})

app.post(URL_UPLOAD_USER_FEEDBACK, (req, res) => {
    if (utils.checkParameters(CHECK_UPLOAD_USER_FEEDBACK, req.body)) {
        logger.info('info', URL_UPLOAD_USER_FEEDBACK)
        let token = req.body.token
        let userId = req.body.userId
        let feedbackContent = req.body.feedbackContent
        let feedbackStatus = req.body.feedbackStatus
        let feedbackDate = req.body.feedbackDate
        let sql = 'use smartSystem;insert into feedbackinfo values("' + feedbackContent + '", ' + userId + ', "' + feedbackStatus + '", "' + feedbackDate + '", NULL);'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv) {
                        logger.info('info', '{"msg":"上传成功"}')
                        res.send('{"msg":"上传成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"上传异常"}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPLOAD_USER_ORDER, (req, res) => {
    if (utils.checkParameters(CHECK_UPLOAD_USER_ORDER, req.body)) {
        logger.info('info', URL_UPLOAD_USER_ORDER)
        let token = req.body.token
        let orderNum = req.body.orderNum
        let orderContent = req.body.orderContent
        let orderDate = req.body.orderDate
        let userId = req.body.userId
        let classification = req.body.classification
        let orderStatus = req.body.orderStatus
        let sql = 'use smartSystem;insert into orderinfo values("' + orderNum + '", "' + orderContent + '", "' + orderStatus + '", "' + classification + '", "' + orderDate + '", NULL, ' + userId + ');'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv) {
                        logger.info('info', '{"msg":"上传成功"}')
                        res.send('{"msg":"上传成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"上传异常"}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPLOAD_COMMENTS, (req, res) => {
    if (utils.checkParameters(CHECK_UPLOAD_COMMENTS, req.body)) {
        logger.info('info', URL_UPLOAD_COMMENTS)
        let token = req.body.token
        let userId = req.body.userId
        let commentContent = req.body.commentContent
        let commentStatus = "暂未审核"
        let commentDate = req.body.commentDate
        let classification = req.body.classification
        let targetId = req.body.targetId
        let sql = ""

        //自动匹配目标评论并上传
        if(classification === "news" || classification === "activity" || classification === "hospital" || classification === "oldHome") {
            if(classification === "news") {
                sql = 'use smartSystem;insert into commentinfo values("' + commentContent + '", ' + userId + ', "' + commentStatus + '", "' + commentDate + '", "' + classification + '", null, null, '+targetId+', null, null);'
            } else if(classification === "activity") {
                sql = 'use smartSystem;insert into commentinfo values("' + commentContent + '", ' + userId + ', "' + commentStatus + '", "' + commentDate + '", "' + classification + '", null, '+targetId+', null, null, null);'
            } else if(classification === "hospital") {
                sql = 'use smartSystem;insert into commentinfo values("' + commentContent + '", ' + userId + ', "' + commentStatus + '", "' + commentDate + '", "' + classification + '", null, null, null, '+targetId+', null);'
            } else if(classification === "oldHome") {
                sql = 'use smartSystem;insert into commentinfo values("' + commentContent + '", ' + userId + ', "' + commentStatus + '", "' + commentDate + '", "' + classification + '", null, null, null, null, '+targetId+');'
            }

            checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
                if (rv) {
                    utils.startOperations(pool, sql).then((rv) => {
                        if(rv) {
                            logger.info('info', '{"msg":"上传成功"}')
                            res.send('{"msg":"上传成功"}')
                        } else {
                            logger.info('info', rv)
                            res.status(500).send('{"msg":"上传异常"}')
                        }
                    })
                } else {
                    logger.info('info', '{"msg":"密钥错误"}')
                    res.status(406).send('{"msg":"密钥错误"}')
                }
            })
        } else {
            logger.info('info', '{"msg":"未进行任何操作", "warn":"分类错误"}')
            res.status(200).send('{"msg":"未进行任何操作", "warn":"分类错误"}')
        }

    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_COMMENTS_LIST, (req, res) => {
    logger.info('info', URL_GET_COMMENTS_LIST)
    if(utils.checkParameters(CHECK_GET_COMMENTS_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let classification = req.body.classification
        let targetId = req.body.targetId
        let sql_templates = []
        
        let parameters = [[targetId, classification], [targetId, classification, (pageNum - 1) * pageSize, pageSize]]
        if(classification === "news" || classification === "activity" || classification === "hospital" || classification === "oldHome") {
            if(classification === "news") {
                sql_templates.push('select count(*) as totalCount from commentInfo where newsId = ? and classification = ?;')
                sql_templates.push('select commentContent, commentStatus, commentDate, classification from commentInfo where newsId = ? and classification = ? limit ?, ?;') 
            } else if(classification === "activity") {
                sql_templates.push('select count(*) as totalCount from commentInfo where activityId = ? and classification = ?;')
                sql_templates.push('select commentContent, commentStatus, commentDate, classification from commentInfo where activityId = ? and classification = ? limit ?, ?;') 
            } else if(classification === "hospital") {
                sql_templates.push('select count(*) as totalCount from commentInfo where hospitalId = ? and classification = ?;')
                sql_templates.push('select commentContent, commentStatus, commentDate, classification from commentInfo where hospitalId = ? and classification = ? limit ?, ?;') 
            } else if(classification === "oldHome") {
                sql_templates.push('select count(*) as totalCount from commentInfo where oldHomeId = ? and classification = ?;')
                sql_templates.push('select commentContent, commentStatus, commentDate, classification from commentInfo where oldHomeId = ? and classification = ? limit ?, ?;') 
            }       
            checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
                if (rv) {
                    utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                        if(rv.length !== 0) {
                            let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                            let isNext = totalPage > pageNum ? TRUE : FALSE
                            logger.info('info', rv)
                            res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                        } else {
                            logger.info('info', rv)
                            res.status(500).send('{"msg":"查询失败"}')
                        }
                    }).catch(err => {
                        console.log(err)
                        logger.info('info', rv)
                        res.status(406).send('{"msg":"查询异常"}')
                    })
                } else {
                    logger.info('info', '{"msg":"密钥错误"}')
                    res.status(406).send('{"msg":"密钥错误"}')
                }
                })
        }

        else {
            logger.info('info', '{"msg":"未进行任何操作", "warn":"分类错误"}')
            res.status(200).send('{"msg":"未进行任何操作", "warn":"分类错误"}')
        }
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})
//新闻模块接口


app.post(URL_SEARCH_NEWS, (req, res) => {
    logger.info('info', URL_SEARCH_NEWS)
    if(utils.checkParameters(CHECK_SEARCH_NEWS, req.body)) {
        let token = req.body.token
        let userId = req.body.userId
        let keywords = req.body.keywords
        let sql = 'use smartSystem;select newsUrl, keywords, title, publishDate, classification from newsInfo where title like "%'+keywords+'%";' 
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_NEWS_DETAILS, (req, res) => {
    logger.info('info', URL_GET_NEWS_DETAILS)
    if(utils.checkParameters(CHECK_GET_NEWS_DETAIL, req.body)) {
        let newsId = req.body.newsId
        let userId = req.body.userId
        let token = req.body.token;
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select * from newsInfo where newsId = "'+ newsId +'";'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_NEWS_LIST, (req, res) => {
    logger.info('info', URL_GET_NEWS_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from newsInfo;',
                            'select newsUrl, keywords, title, publishDate, classification from newsInfo limit ?, ?;']
        let parameters = [[], [(pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_LIKE_NEWS_DETAILS, (req, res) => {
    if(utils.checkParameters(CHECK_LIKE_NEWS_DETAILS, req.body)) {
        let newsId = req.body.newsId
        let userId = req.body.userId
        let token = req.body.token
        let like = req.body.like
        let createDate = sillydate.format(new Date(), 'YYYY-MM-DD HH:mm')
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select count(*) as totalCount from historyInfo where newsId = '+ newsId +' and classification = "like" and userId = '+ userId +';', 
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                if(like === 1) {
                    utils.startOperations(pool, sql).then((rv) => {
                        if(rv[0].totalCount === 0) {  
                            let sql_templates = ['use smartSystem;insert into historyInfo values("like", ?, ?, null, ?, null);',
                                                 'update newsinfo set likes = likes + 1 where newsId = ?;']
                            let parameters = [[createDate, newsId, userId], [newsId]]
                            utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                                if(rv.length !== 0) {
                                    logger.info('info', '{"msg":"点赞成功"}')
                                    res.send('{"msg":"点赞成功"}')
                                } else {
                                    logger.info('info', '{"msg":"查询异常"}')
                                    res.status(500).send('{"msg":"查询异常"}')
                                }                                    
                            }).catch((err) => {
                                logger.info('info', '{"msg":"更改异常"}')
                                logger.error('error', err)

                                console.log(err)
                                res.status(402).send('{"msg":"更改异常"}')
                            })
                        } else {
                            logger.info('info', '{"msg":"未进行任何操作", "warn":"已点赞"}')
                            res.send('{"msg":"未进行任何操作", "warn":"已点赞"}')
                        }
                    })
                } else if(like === 0) {
                    utils.startOperations(pool, sql).then((rv) => {
                        let sql_templates = ['delete from historyInfo where newsId = ? and classification = "like" and userId = ?',
                        'update newsinfo set likes = likes - 1 where newsId = ?']
                        let parameters = [[newsId, userId], [newsId]]
                        if(rv[0].totalCount !== 0) {
                            utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                                if(rv.length !== 0) {
                                    logger.info('info', '{"msg":"取消点赞成功"}')
                                    res.send('{"msg":"取消点赞成功"}')
                                } else {
                                    logger.info('info', '{"msg":"更改异常"}')
                                    res.status(500).send('{"msg":"更改异常"}')
                                }   
                            }).catch((err) => {
                                logger.info('info', '{"msg":"更改异常"}')
                                logger.error('error', err)
                                res.status(402).send('{"msg":"更改异常"}')
                            })
                        } else {
                            logger.info('info', '{"msg":"未进行任何操作", "warn":"尚未点赞"}')
                            res.send('{"msg":"未进行任何操作", "warn":"尚未点赞"}')
                        }
                    })
                } else {
                    logger.info('info', '{"msg":"非法参数"}')
                    res.status(406).send('{"msg":"非法参数"}')
                }

            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        
        })
    } else {
        logger.info('info', '{"msg":"参数异常"}')
        res.status(406).send('{"msg":"参数异常"}')
    }
})

app.post(URL_VIEW_NEWS_DETAILS, (req, res) => {
    if(utils.checkParameters(CHECK_VIEW_NEWS_DETAILS, req.body)) {
        let newsId = req.body.newsId
        let userId = req.body.userId
        let token = req.body.token
        let view = req.body.view
        let createDate = sillydate.format(new Date(), 'YYYY-MM-DD HH:mm')
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select count(*) as totalCount from historyInfo where newsId = '+ newsId +' and classification = "view" and userId = '+ userId +';', 
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                if(view === 1) {
                    utils.startOperations(pool, sql).then((rv) => {
                        if(rv[0].totalCount === 0) {  
                            let sql_templates = ['use smartSystem;insert into historyInfo values("view", ?, ?, null, ?, null);',
                                                 'update newsinfo set viewers = viewers + 1 where newsId = ?;']
                            let parameters = [[createDate, newsId, userId], [newsId]]
                            utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                                if(rv.length !== 0) {
                                    logger.info('info', '{"msg":"浏览成功"}')
                                    res.send('{"msg":"浏览成功"}')
                                } else {
                                    logger.info('info', '{"msg":"查询异常"}')
                                    res.status(500).send('{"msg":"查询异常"}')
                                }                                    
                            }).catch((err) => {
                                logger.info('info', '{"msg":"更改异常"}')
                                logger.error('error', err)

                                console.log(err)
                                res.status(402).send('{"msg":"更改异常"}')
                            })
                        } else {
                            logger.info('info', '{"msg":"未进行任何操作", "warn":"已浏览"}')
                            res.send('{"msg":"未进行任何操作", "warn":"已浏览"}')
                        }
                    })
                } else if(view === 0) {
                    utils.startOperations(pool, sql).then((rv) => {
                        let sql_templates = ['delete from historyInfo where newsId = ? and classification = "view" and userId = '+userId+';',
                        'update newsinfo set viewers = viewers - 1 where newsId = ?']
                        let parameters = [[newsId], [newsId]]
                        if(rv[0].totalCount !== 0) {
                            utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                                if(rv.length !== 0) {
                                    logger.info('info', '{"msg":"取消浏览成功"}')
                                    res.send('{"msg":"取消浏览成功"}')
                                } else {
                                    logger.info('info', '{"msg":"更改异常"}')
                                    res.status(500).send('{"msg":"更改异常"}')
                                }   
                            }).catch((err) => {
                                logger.info('info', '{"msg":"更改异常"}')
                                logger.error('error', err)
                                res.status(402).send('{"msg":"更改异常"}')
                            })
                        } else {
                            logger.info('info', '{"msg":"未进行任何操作", "warn":"尚未浏览"}')
                            res.send('{"msg":"未进行任何操作", "warn":"尚未浏览"}')
                        }
                    })
                } else {
                    logger.info('info', '{"msg":"非法参数"}')
                    res.status(406).send('{"msg":"非法参数"}')
                }

            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        
        })
    } else {
        logger.info('info', '{"msg":"参数异常"}')
        res.status(406).send('{"msg":"参数异常"}')
    }
})

app.post(URL_GET_HISTORY_NEWS_LIKE_LIST, (req, res) => {
    logger.info('info', URL_GET_HISTORY_NEWS_LIKE_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from historyInfo where userId = ? and classification = "like";',
                            'select newsUrl, keywords, title, publishDate, classification from newsInfo where newsId in (select newsId from historyInfo where userId = ? and classification = "like") limit ?, ?;']
        let parameters = [[userId], [userId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_HISTORY_NEWS_VIEW_LIST, (req, res) => {
    logger.info('info', CHECK_GET_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from historyInfo where userId = ? and classification = "view";',
                            'select newsUrl, keywords, title, publishDate, classification from newsInfo where newsId in (select newsId from historyInfo where userId = ? and classification = "view") limit ?, ?;']
        let parameters = [[userId], [userId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})


app.post(URL)

//新闻获取
app.get(crawlerTencent, (req, res) => {
    logger.info('info', '{"msg":"新闻爬取指令已发出}')
    res.status(406).send('{"msg":"新闻爬取指令已发出"}')
    tencentNews.start(pool).then((rv) => {
        if(rv !== "出现异常") {
            logger.info('info', '{"msg":"新闻爬取发生异常"}')
        }
    })
})

//医疗预约模块

app.post(URL_GET_HOSPITAL_LIST, (req, res) => {
    logger.info('info', URL_GET_HOSPITAL_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from hospitalInfo;',
                            'select * from hospitalInfo limit ?, ?;']
        let parameters = [[], [(pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_DEPARTMENT_LIST, (req, res) => {
    logger.info('info', URL_GET_DEPARTMENT_LIST)
    if(utils.checkParameters(CHECK_GET_DEPARTMENT_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let hospitalId = req.body.hospitalId
        let sql_templates = ['select count(*) as totalCount from departmentInfo where hospitalId = ?;',
                            'select * from departmentInfo where hospitalId = ? limit ?, ?;']
        let parameters = [[hospitalId], [hospitalId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_DOCTOR_LIST, (req, res) => {
    logger.info('info', URL_GET_DOCTOR_LIST)
    if(utils.checkParameters(CHECK_GET_DOCTOR_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let departmentId = req.body.departmentId
        let sql_templates = ['select count(*) as totalCount from doctorInfo where departmentId = ?;',
                            'select * from doctorInfo where departmentId = ? limit ?, ?;']
        let parameters = [[departmentId], [departmentId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_AVAILABLE_LIST, (req, res) => {
    logger.info('info', URL_GET_AVAILABLE_LIST)
    if(utils.checkParameters(CHECK_GET_AVAILABLE_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let doctorId = req.body.doctorId
        let sql_templates = ['select count(*) as totalCount from restInfo where doctorId = ?;',
                            'select * from restinfo where doctorId = ? limit ?, ?;']
        let parameters = [[doctorId], [doctorId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPLOAD_HOPORDER, (req, res) => {
    logger.info('info', URL_UPLOAD_HOPORDER)
    if(utils.checkParameters(CHECK_UPLOAD_HOPORDER, req.body)) {
        let token = req.body.token
        let userId = req.body.userId
        let doctorId = req.body.doctorId
        let departmentId = req.body.departmentId
        let hospitalId = req.body.hospitalId
        let orderDate = req.body.orderDate
        let createDate = req.body.createDate
        let patientId = req.body.patientId
        let sql_templates = ['insert into hopOrderInfo values(?,null,?,?,?,?,?);',
                            'update doctorInfo set rest = rest - 1 where doctorId = ?;']
        let parameters = [[hospitalId, departmentId, patientId, userId, orderDate, createDate], [doctorId]]
        let sql = 'use smartSystem;select rest from doctorInfo where doctorId = doctorId;'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv[0].rest === 0) {
                        logger.info('info', rv)
                        res.send('{"msg":"预约失败", "warn":"没有空余位置"}')
                    } else {
                        utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                            if(rv.length !== 0) {
                                logger.info('info', rv)
                                res.send('{"msg":"预约成功"}')
                            } else {
                                logger.info('info', rv)
                                res.status(500).send('{"msg":"预约失败"}')
                            }
                        }).catch(err => {
                            logger.info('info', rv)
                            res.status(406).send('{"msg":"预约失败"}')
                        })
                    }
                })

            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_HOPORDER_LIST, (req, res) => {
    logger.info('info', URL_GET_HOPORDER_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from hoporderinfo where userId = ?;',
        'select hospitalName, departmentName, orderDate, createDate, hopId from hospitalinfo, departmentinfo, hoporderinfo where hoporderinfo.userId = '+userId+' limit ?,?;']
        let parameters = [[userId], [userId, (pageNum - 1) * pageSize, pageSize]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    console.log(err)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_HOPORDER_DETAILS, (req, res) => {
    logger.info('info', URL_GET_HOPORDER_DETAILS)
    if(utils.checkParameters(CHECK_GET_HOPORDER_DETAILS, req.body)) {
        let userId = req.body.userId
        let token = req.body.token
        let hopId = req.body.hopId
        //token = req.body.token.replace(/"/g, '');
        sql = 'use smartSystem;select patientName, birth, phoneNum, sex, hospitalName, departmentName, doctorName, createDate, orderDate from patientinfo, hospitalinfo, departmentinfo, doctorinfo, hoporderinfo where hoporderinfo.userId = '+userId+' and hopId = '+hopId+';'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv.length === 0) {
                        logger.info('info', '{"msg":"查询异常"}')
                        res.status(500).send('{"msg":"查询异常"}')
                    } else {
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "data":' + JSON.stringify(rv) + '}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_GET_PATIENT_LIST, (req, res) => {
    logger.info('info', URL_GET_PATIENT_LIST)
    if(utils.checkParameters(CHECK_GET_LIST, req.body)) {
        let pageSize = req.body.pageSize
        let pageNum = req.body.pageNum
        let token = req.body.token
        let userId = req.body.userId
        let sql_templates = ['select count(*) as totalCount from patientinfo where userId = ?;',
                            'select * from patientinfo limit ?, ? where userId = ?;']
        let parameters = [[userId], [(pageNum - 1) * pageSize, pageSize, userId]]
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    if(rv.length !== 0) {
                        let totalPage = Math.ceil(rv[0][0].totalCount / pageSize)
                        let isNext = totalPage > pageNum ? TRUE : FALSE
                        logger.info('info', rv)
                        res.send('{"msg":"查询成功", "isNext":'+isNext+', "data":' + JSON.stringify(rv[1]) + '}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"查询失败"}')
                    }
                }).catch(err => {
                    logger.info('info', rv)
                    res.status(406).send('{"msg":"查询异常"}')
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
        
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPLOAD_PATIENT, (req, res) => {
    if (utils.checkParameters(CHECK_UPLOAD_PATIENT, req.body)) {
        logger.info('info', URL_UPLOAD_PATIENT)
        let token = req.body.token
        let userId = req.body.userId
        let patientId = req.body.patientId
        let patientName = req.body.patientName
        let sex = req.body.sex
        let birth = req.body.birth
        let address = req.body.address
        let phoneNum = req.body.phoneNum
        let sql = 'use smartSystem;insert into patientinfo values("' + patientName + '", "' + birth + '", "' + phoneNum + '", "' + sex + '", "'+ address +'", '+ patientId +', null);'
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                utils.startOperations(pool, sql).then((rv) => {
                    if(rv) {
                        logger.info('info', '{"msg":"上传成功"}')
                        res.send('{"msg":"上传成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"上传异常"}')
                    }
                })
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } else {
        logger.info('info', '{"msg":"非法参数"}')
        res.status(406).send('{"msg":"非法参数"}')
    }
})

app.post(URL_UPDATE_PATIENT, (req, res) => {
    logger.info('info', URL_UPDATE_PATIENT)
    let sql_templates = []
    let parameters = []
    try {
        let userId = req.body.userId
        let token = req.body.token
        checkToken(token, USER_SECRETORPRIVATEKEY, userId).then((rv) => {
            if (rv) {
                for(item in req.body) {
                    if (item === "token" || item === "userId") {
                        continue
                    } else {
                        sql_templates.push('update patientinfo set '+item+' = ? where userId = '+userId+';')
                        parameters.push([req.body[item]])
                    }
                }
                logger.info('info', sql_templates)
                logger.info('info', parameters)
                utils.startTransaction(pool, sql_templates, parameters).then((rv) => {
                    logger.info('info', rv)
                    if (rv.length !== 0) {
                        logger.info('info', '{"msg":"更改成功"}')
                        res.send('{"msg":"更改成功"}')
                    } else {
                        logger.info('info', rv)
                        res.status(500).send('{"msg":"更改失败}')
                    }
                }).catch((err) => {
                    logger.error('error', err)
                    res.status(406).send('{"msg":"更改异常"}')
                }) 
            } else {
                logger.info('info', '{"msg":"密钥错误"}')
                res.status(406).send('{"msg":"密钥错误"}')
            }
        })
    } catch (err) {
        logger.info('info', '{"msg":"更改异常"}')
        logger.error('error', err)
        res.status(402).send('{"msg":"更改异常"}')
    }
})

app.listen(PORT)
logger.info('info', "The service is running on port: " + PORT)

//创建token，有效期为1h
function createToken(content, key) {
	let token = jsonwebtoken.sign(content, key, {
		expiresIn: 60 * 60 * 1
	});
	return token;
}

//json格式校验
function isJsonString(str) {
	try {
        str = JSON.stringify(str)
		if (typeof JSON.parse(str) == "object") {
			return TRUE;
		}
	} catch(e) {
		return FALSE;
	}
}

function checkToken(token, key, userId) {
    return new Promise((resolve, reject) => {
        jsonwebtoken.verify(token, key, (err, decode) => {
            if (err) {
                resolve(FALSE)
            } else {
                if (decode.userId === userId) {
                    resolve(TRUE)
                } else {
                    resolve(FALSE)
                }
            }
        }) 
    })
}

//设置网络（数据库服务器，以及后端服务器）
// function setNet(ip, portNum, host, post, user, password, http) {
//     PORT = portNum != "" ? portNum : 8888
//     IP = ip != "" ? ip : "127.0.0.1"
//     HOST = host != "" ? host : "localhost" 
//     USER = user != "" ? user : "root"
//     PASSWORD = password != "" ? password : ""
//     HTTP = http != "" ? http : "http"
//     POST = post != "" ? post : "3306"
// }

